/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[FileDownloadServlet.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package file.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import file.upload.commons.FileUploadConstants;

/**
 * 文件下载Servlet
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(value = "/downloadServlet")
public class FileDownloadServlet extends HttpServlet {

	private static final long serialVersionUID = -1288103500071114596L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Properties properties = (Properties) request.getServletContext().getAttribute("fileConfig");
		String filePath = properties.getProperty(FileUploadConstants.FILE_PATH);

		String fileName = request.getParameter("fileName");
		File downloadFile = new File(filePath + File.separator + fileName);
		if (!downloadFile.exists()) {
			request.setAttribute("message", "要下载的资源已被删除");
			request.getRequestDispatcher("/listFileServlet").forward(request, response);
			return;
		}

		String realFileName = fileName.substring(fileName.indexOf('_') + 1);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html,charset=UTF-8");
		response.setContentType("application/x-msdownload");
		response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realFileName, "UTF-8"));

		FileInputStream in = new FileInputStream(downloadFile);
		byte[] buffer = new byte[1024];
		int length = 0;
		OutputStream out = response.getOutputStream();
		while ((length = in.read(buffer)) != -1) {
			out.write(buffer, 0, length);
		}
		in.close();
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
